package cn.com.jcoo;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@EnableAspectJAutoProxy(exposeProxy = true)
@Aspect
public class AccessAuthAspect {

    private final AccessService accessService;

    public AccessAuthAspect(AccessService accessService) {
        this.accessService = accessService;
    }


    @Pointcut("@annotation(cn.com.jcoo.AccessAuth)")
    public void pointcut() {
    }


    @Before(value = "pointcut()")
    public void accessAuthCheck(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        // 获取方法上的注解
        AccessAuth accessAuth = method.getAnnotation(AccessAuth.class);
        if (accessAuth == null) {
            // 获取类上的注解
            Class<?> targetClass = joinPoint.getTarget().getClass();
            accessAuth = targetClass.getAnnotation(AccessAuth.class);
            if (accessAuth == null) {
                return;
            }
        }
        String code = accessAuth.code();
        List<String> accessCodes = accessService.getAccessCodes();
        if (accessCodes == null || accessCodes.isEmpty()) {
            throw new AccessAuthException("访问权限认证失败");
        }

        if (accessCodes.stream().anyMatch(e -> Objects.equals(e, code))) {
            return;
        }
        throw new AccessAuthException("访问权限认证失败");

    }
}
